<template>
  <div class="mb-info" v-loading="loading">
    <div class="mb-detail">
      <div class="mb-detail-hd-icon">
        <JIcon :icon="DFT_ICONS.api"/>
      </div>
      <div class="mb-detail-hd-info" style="flex: 0;">
        <div class="mb-detail-hd-title">平台低代码接口</div>
      </div>
      <div class="api-file-path">
        <el-radio-group size="mini" v-model="apiType">
          <el-radio-button label="mapi">低码接口</el-radio-button>
          <el-radio-button label="system">系统接口</el-radio-button>
        </el-radio-group>
      </div>
      <el-button
        class="app-group-add-btn"
        type="text"
        size="small"
        @click="handleShowCreateOption">
        <template #icon>
          <JIcon :icon="DFT_ICONS.add"/>
        </template>
        系统/低码接口
      </el-button>
    </div>
    <el-alert
      v-if="apiType === 'system'"
      type="warning"
      show-icon
      :closable="false"
      style="border-radius: 0px;border-bottom: 1px solid #e6eaf0;"
      title="系统接口仅支持POST请求。">
      <div>系统接口调用方式：this.$japi._post([ 接口URL ], params)</div>
    </el-alert>
    <el-alert
      v-else
      type="warning"
      show-icon
      :closable="false"
      style="border-radius: 0px;border-bottom: 1px solid #e6eaf0;"
      title="微接口仅支持POST请求。">
      <div>微接口调用方式：this.$japi.microsvc.mapi([ 接口URL ], params)</div>
    </el-alert>
    <div class="m-table-container" ref="datasContainer">
      <el-table
        :data="apis"
        size="mini"
        row-key="mb_id"
        :tree-props="{ children: 'subs' }"
        :height="datasTableHeight"
        class="m-table"
        indent="0"
        default-expand-all>
        <el-table-column prop="api_rest" label="类型" width="50" align="center">
          <template #default="scope">
            <JIcon
              v-if="scope.row.api_rest === 'system'"
              :icon="DFT_ICONS.platform"
              class="fa fa-globe"
              style="color: #F56C6C;"
              v-tippy="{ arrow: true }" content="系统接口"/>
            <JIcon
              v-else
              :icon="DFT_ICONS.custom"
              class="fa fa-copyright"
              style="color: #96E1ff;"
              v-tippy="{ arrow: true }"
              content="低码接口"/>
          </template>
        </el-table-column>
        <el-table-column prop="api_name" label="接口名称" width="280">
          <template #default="scope">
            <div
              v-tippy="{ arrow: true, placement: 'top-start' }"
              :content="scope.row.remark || scope.row.api_name">
              {{ scope.row.api_name }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="api_uuid" label="接口URL">
          <template #default="scope">
            <div
              class="text-copy-wrap"
              v-copy="`${ getApiUrl(scope.row) }`"
              v-tippy="{ arrow: true, placement: 'right' }"
              content="点击复制">
              {{ getApiUrl(scope.row) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="api_code" label="接口编码（方法名）" width="240"></el-table-column>
        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="text"
              v-tippy="{ arrow: true }"
              content="修改"
              @click="handleOptionEdit(scope.row)"
            >
              <template #icon>
                <JIcon :icon="DFT_ICONS.edit" />
              </template>
            </el-button>
            <el-button
              v-if="scope.row.api_id"
              size="small"
              type="text"
              v-tippy="{ arrow: true }"
              content="删除"
              @click="handleOptionRemove(scope.row)">
              <template #icon>
                <JIcon :icon="DFT_ICONS.delete" />
              </template>
            </el-button>
            <el-button
              size="small"
              type="text"
              v-tippy="{ arrow: true }"
              content="复制调用链接"
              @click="handleCopyUrl(scope.row)">
<!--              <template #icon>
                <JIcon :icon="DFT_ICONS.copy" />
              </template>-->
              复制URL
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog
      v-model="formApiWinShow"
      :title="formApiWinName"
      :close-on-click-modal="false"
      :append-to-body="true">
      <form-api
        v-if="formApiWinShow"
        :current-data="selectedData"
        :api-type="apiType"
        :action-type="actionType"
        @close="handleFormClose" />
    </el-dialog>
    <ResizeObserver @notify="handleResize"/>
  </div>
</template>

<script setup>
import {ref, reactive, watch, onMounted, computed, nextTick} from 'vue';
import { ResizeObserver } from 'vue3-resize';
import formApi from './form-api-plat.vue';
import _ from 'lodash';
import {api} from '@jzl/api';
import {useCommonStore} from "@jzl/stores";
import {DFT_ICONS} from "@jzl/icons"; // 假设你有一个 useUtils 的组合式函数

const props = defineProps({
  currentData: Object
});

const emit = defineEmits([]);

const DEFAULT_FORM = {
  svc_module_uuid: '',
  svc_module_code: '',
  svc_module_name: '',
  svc_module_type: 1,
  svc_module_store: 1,
  data_key: '',
  service_id: '',
  app_id: -1,
};

const loading = ref(false);
const selectedData = ref(null);
const apiType = ref("mapi");
const actionType = ref('view'); // createOption | createOptionBefore | createOptionChild | edit
const datasTableHeight = ref(500);
const allApis = ref([]);
const formApiWinName = ref('新增/修改平台微接口');
const formApiWinShow = ref(false);
const flowWinShow = ref(false);
const flowWinName = ref('');
const apiData = ref(null);
const appId = ref(null);
const type = ref(4);
const form = ref(null);
const formFuncWinName = ref('');
const formFuncWinShow = ref(false);
const datasContainer = ref(null);

const loginUser = computed(() => useCommonStore().loginUser)
const project = computed(() => useCommonStore().project)

const moduleApiRemark = computed(() => {
  let apiUrl = `/api/core/mapi/[ 接口URL ]`;
  return `当前接口模块调用方式：${apiUrl}`;
});

const isSuperAdmin = computed(() => _.get(loginUser.value, 'type') === '_SUPER');

const apis = computed(() => {
  return _.filter(allApis.value, api => {
    if (apiType.value === 'system') {
      return api.api_rest === 'system';
    } else {
      return api.api_rest !== 'system';
    }
  });
});

const init = async () => {
  await loadApis();
  handleResize();
};

const handleResize = () => {
  nextTick(() => {
    if (!datasContainer.value) return;

    let rect = datasContainer.value.getBoundingClientRect();
    let height = _.get(rect, 'height');
    if (height > 0) {
      datasTableHeight.value = height;
    }
  });
};

const loadApis = async () => {
  allApis.value = [];
  loading.value = true;
  let apis = await api.services.getPlatApis();
  loading.value = false;
  allApis.value = apis;
};

const handleClearCache = async () => {
  let moduleCode = _.get(props.currentData, 'svc_module_code');
  let appCode = _.get(props.currentData, "app.group_code");

  let ret = await api.services.clearCache(appCode, moduleCode);

  if (ret) {
    $jui.toast('操作成功！');
  }
};

const handleShowCreateOption = () => {
  selectedData.value = null;
  actionType.value = 'createOption';
  formApiWinName.value = '新增API';
  formApiWinShow.value = true;
};

const handleFormClose = async (isUpdate) => {
  formApiWinShow.value = false;
  await init();
};

const handleOptionEdit = (option) => {
  let name = _.get(option, 'api_name');

  selectedData.value = option;
  actionType.value = 'edit';
  formApiWinName.value = `【${name}】接口修改`;
  formApiWinShow.value = true;
};

const handleOptionRemove = (option) => {
  let dt = option;

  if (!dt) return;

  let msg = `确定删除【${dt.api_name}】?`;
  $jui.confirm(msg).then(async () => {
    loading.value = true;

    let ret = await api.services.apiRemove(dt.api_id);

    if (ret) {
      await init();
    }

    loading.value = false;
  }).catch(() => {
    // 取消操作
  });
};

const handleApiTest = async (api) => {
  let err, ret;
  let moduleCode = _.get(props.currentData, 'svc_module_code');
  let appCode = _.get(props.currentData, "app.group_code");
  let apiCode = _.get(api, 'api_code');
  let url = `/api/core/mapi/${appCode}/${moduleCode}/${apiCode}`;

  [err, ret] = await to(api._post(url));

  if (err) {
    ElMessage.error(`调用失败：${_.get(err, 'message')}！`);
  } else {
    ElMessage.success(JSON.stringify(_.get(ret, 'data')));
  }
};

const getApiUrl = (data) => {
  let uris = [];
  let fn = _.get(data, 'api_funame');
  let ac = _.get(data, 'api_code');

  if (fn) uris.push(fn);
  if (ac) uris.push(ac);

  let uriStr = _.join(uris, "/");
  return uriStr;
};

const handleCopyUrl = (data) => {
  let apiUrl = getApiUrl(data);
  if (apiUrl) {
    $utils.copyText(`/api/core/mapi/${apiUrl}`);
  }
};

const handleSave = async () => {
  let form = _.cloneDeep(form.value);
  let tip = '';

  if (!form) return;

  loading.value = true;

  let funcId = _.get(form, 'func_id');
  let id = _.get(props.currentData, "svc_module_id");
  let ret;

  if (funcId) {
    ret = await api.services.moduleFuncUpdate(id, form);
  } else {
    ret = await api.services.moduleFuncCreate(id, form);
  }

  if (ret) {
    formFuncWinShow.value = false;
    await init();
  }

  loading.value = false;
};

onMounted(() => {
  init();
});

watch(() => props.currentData, () => {
  init();
}, {deep: true});
</script>

<style lang="scss" scoped>
.api-file-path {
  flex: 1;
  font-weight: bold;
  text-align: center;
}
</style>
